<?php 
namespace xfyzf\api\controller;
use xfyzf\api\controller\payconf;
use xfyzf\api\controller\epaysdk;
use lib\Commontc;
class Index{
    public function submit_pay(){
        global $httphost,$conf;
        $getdata  = input("get");
        if(!empty($getdata['type']) && !empty($getdata['trade_no'])){
            $notify_url = $httphost."/User/api.php?s=notify_url";
            $return_url = $httphost."/User/login";
            $addtime = date("Y-m-d H:i:s",time());
            $ip   = http_ip();
            $type = $getdata['type'];
            $trade_no = $getdata['trade_no'];
            $name     = '申请商户';
            $twelveHoursAgo = time() - 3600 * 12;
            $twelveHoursAgoStr = date('Y-m-d H:i:s', $twelveHoursAgo);
            $sql = "SELECT COUNT(*) as count FROM pay_order WHERE ip = '$ip' AND UNIX_TIMESTAMP(addtime) > UNIX_TIMESTAMP('$twelveHoursAgoStr') AND status='0'";
            if(executeSQLQuery($sql)['count'] > 15){
                Commontc::falsetc('由于您12小时内发起的订单并且未支付过多已对您进行限制处理，请12小时后再发起重试！',rethreffun('./login'));
            }
            $money = $conf['reg_pay_price'];
            if(!is_numeric($money) || $money < 0){
                 Commontc::falsetc('金额不合法！',rethreffun('./login'));
             }
            $sql = "SELECT * FROM pay_user WHERE pid='{$conf['zero_pid']}' limit 1";
            $row = executeSQLQuery($sql);
            $parameter = array(
            		"type" => $type,
            		"notify_url"	=> $notify_url,
            		"return_url"	=> $return_url,
            		"out_trade_no"	=> $trade_no,
            		"name"	=> $name,
            		"money"	=> $money,
            		"sitename"	=> $conf['sitename'],
            		"ip"       =>$ip
            );
            $this->Payment_channel($parameter,$row);
        }
        http_response_code(503);
    }
    public function submit_sdkpay(){
        global $httphost,$conf;
        $postdata = input();
        if(!empty($postdata['WIDout_trade_no']) && !empty($postdata['WIDsubject']) && !empty($postdata['WIDtotal_fee']) && !empty($postdata['type'])){
            $notify_url = $httphost."/User/api.php?s=notify_url";
            $return_url = $httphost."/SDK/cg";
            $addtime = date("Y-m-d H:i:s",time());
            $ip   = http_ip();
            $type = $postdata['type'];
            $trade_no = $postdata['WIDout_trade_no'];
            $name     = $postdata['WIDsubject'];
            $twelveHoursAgo = time() - 3600 * 12;
            $sql = "SELECT COUNT(*) as count FROM pay_order WHERE ip = '$ip' AND UNIX_TIMESTAMP(addtime) > UNIX_TIMESTAMP('$twelveHoursAgoStr') AND status='0'";
            if(executeSQLQuery($sql)['count'] > 15){
                 Commontc::falsetc('由于您12小时内发起的订单并且未支付过多已对您进行限制处理，请12小时后再发起重试！',rethreffun('./login'));
            }
            $money = $postdata['WIDtotal_fee'];
            if(!is_numeric($money) || $money < 0){
                 Commontc::falsetc('金额不合法！',rethreffun('./login'));
            }
            $sql = "SELECT * FROM pay_user WHERE pid='{$conf['zero_pid']}' limit 1";
            $row = executeSQLQuery($sql);
            $parameter = array(
            		"type" => $type,
            		"notify_url"	=> $notify_url,
            		"return_url"	=> $return_url,
            		"out_trade_no"	=> $trade_no,
            		"name"	=> $name,
            		"money"	=> $money,
            		"sitename"	=> $conf['sitename'],
            		"ip"       =>$ip
            );
            $this->Payment_channel($parameter,$row);
        }
        http_response_code(503);
    }
    public function submit_usersdk_pay(){
        global $httphost,$userrow;
        $postdata = input();
        if($userrow){
            if(!empty($postdata['WIDout_trade_no']) && !empty($postdata['WIDsubject']) && !empty($postdata['WIDtotal_fee']) && !empty($postdata['type'])){
                $notify_url = $httphost."/User/api.php?s=notify_url";
                $return_url = $httphost."/User/?s=Pay_cs";
                $addtime = date("Y-m-d H:i:s",time());
                $ip   = http_ip();
                $type = $postdata['type'];
                $trade_no = $postdata['WIDout_trade_no'];
                $name     = $postdata['WIDsubject'];
                $money    = $postdata['WIDtotal_fee'];
                if(!is_numeric($money) || $money < 0){
                     Commontc::falsetc('金额不合法！',rethreffun('./login'));
                }
               $parameter = array(
                		"type" => $type,
                		"notify_url"	=> $notify_url,
                		"return_url"	=> $return_url,
                		"out_trade_no"	=> $trade_no,
                		"name"	=> $name,
                		"money"	=> $money,
                		"sitename"	=> $conf['sitename'],
                		"ip"       =>$ip
                ); 
                $this->Payment_channel($parameter,$userrow);
            }
        }
        http_response_code(503);
    }
    
    public function submit_quotapay(){
        global $userrow,$conf,$httphost;
        $postdata = input("post");
        if($userrow){
            if(!empty($postdata['WIDout_trade_no']) && !empty($postdata['WIDsubject']) && !empty($postdata['WIDtotal_fee']) && !empty($postdata['type'])){
                $notify_url = $httphost."/User/api.php?s=notify_url";
                $return_url = $httphost."/User/Pay_Vip";
                $addtime = date("Y-m-d H:i:s",time());
                $ip   = http_ip();
                $type = $postdata['type'];
                $trade_no = $postdata['WIDout_trade_no'];
                $name     = $postdata['WIDsubject'];
                $twelveHoursAgo = time() - 3600 * 12;
                $money = $postdata['WIDtotal_fee'];
                if(!is_numeric($money) || $money < 0){
                    Commontc::falsetc('金额不合法！',rethreffun('./Pay_Vip'));
                }
                $sql = "SELECT * FROM pay_user WHERE pid='{$conf['zero_pid']}' limit 1";
                $row = executeSQLQuery($sql);
                $parameter = array(
                		"type" => $type,
                		"notify_url"	=> $notify_url,
                		"return_url"	=> $return_url,
                		"out_trade_no"	=> $trade_no,
                		"name"	=> $name,
                		"money"	=> $money,
                		"sitename"	=> $conf['sitename'],
                		"ip"       =>$ip
                );
                insertIntoInsideOrder($trade_no,$userrow['pid'],$money, $postdata['WIDsubject'].'|'.$userrow['pid']);
                $this->Payment_channel($parameter,$row);
            }
        }
         http_response_code(503);
    }
    public function submit_payvip(){
        global $userrow,$conf,$httphost;
        $getdata = input("get");
        if($userrow){
            if(!empty($getdata['WIDout_trade_no']) && !empty($getdata['WIDsubject']) && !empty($getdata['type'])){
                
                $notify_url = $httphost."/User/api.php?s=notify_url";
                $return_url = $httphost."/User/Pay_Vip";
                $addtime = date("Y-m-d H:i:s",time());
                $ip   = http_ip();
                $type = $getdata['type'];
                $trade_no = $getdata['WIDout_trade_no'];
                $name     = $getdata['WIDsubject'];
                $twelveHoursAgo = time() - 3600 * 12;
                $sql = "SELECT * FROM pay_insideorder WHERE `pid` =:pid and `order`=:order limit 1";
                $paramsSelect = [
                        'pid' => $userrow['pid'],
                        'order'=>$trade_no
                  ];
                $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
                
                if(!$is)Commontc::falsetc('您未创建订单  请先创建订单后在试！',rethreffun('./Pay_Vip'));
                $money = $conf[$is['beizhu'].'_free_vip_money'];
                if(!is_numeric($money) || $money < 0){
                     Commontc::falsetc('金额不合法！',rethreffun('./Pay_Vip'));
                }
                $sql = "SELECT * FROM pay_user WHERE pid='{$conf['zero_pid']}' limit 1";
                $row = executeSQLQuery($sql);
                $parameter = array(
                		"type" => $type,
                		"notify_url"	=> $notify_url,
                		"return_url"	=> $return_url,
                		"out_trade_no"	=> $trade_no,
                		"name"	=> $name,
                		"money"	=> $money,
                		"sitename"	=> $conf['sitename'],
                		"ip"       =>$ip
                );
               $this->Payment_channel($parameter,$row); 
            }
        }
        http_response_code(503);
    }
    public  function submit_setmenu_pay(){
        global $userrow,$conf,$httphost;
        $getdata  = input("get");
        if($userrow){
            if(!empty($getdata['WIDout_trade_no']) && !empty($getdata['WIDsubject']) && !empty($getdata['type'])){
                $notify_url = $httphost."/User/api.php?s=notify_url";
                $return_url = $httphost."/User/Package";
                $addtime = date("Y-m-d H:i:s",time());
                $ip   = http_ip();
                $type = $getdata['type'];
                $trade_no = $getdata['WIDout_trade_no'];
                $name     = $getdata['WIDsubject'];
                
                $sql = "SELECT * FROM pay_insideorder WHERE `pid` =:pid and `order`=:order limit 1";
                $paramsSelect = [
                        'pid' => $userrow['pid'],
                        'order'=>$trade_no
                ];
                $is = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
                if(!$is)Commontc::falsetc('您未创建订单  请先创建订单后在试！',rethreffun('./Package'));
                $money = $is['money'];
                if(!is_numeric($money) || $money < 0){
                    Commontc::falsetc('金额不合法！',rethreffun('./Package'));
                    
                }
                $sql = "SELECT * FROM pay_user WHERE pid='{$conf['zero_pid']}' limit 1";
                $row = executeSQLQuery($sql);
                $parameter = array(
                		"type" => $type,
                		"notify_url"	=> $notify_url,
                		"return_url"	=> $return_url,
                		"out_trade_no"	=> $trade_no,
                		"name"	=> $name,
                		"money"	=> $money,
                		"sitename"	=> $conf['sitename'],
                		"ip"       =>$ip
                );
                $this->Payment_channel($parameter,$row); 
            }
        }
        http_response_code(503);
    }
    public function submit_quotapackage_pay(){
        global $userrow,$conf,$httphost;
        $postdata = input("post");
        if($userrow){
            if(!empty($postdata['WIDout_trade_no']) || !empty($postdata['WIDsubject']) || !empty($postdata['WIDtotal_fee']) || !empty($postdata['type'])){
                $notify_url = $httphost."/User/api.php?s=notify_url";
                $return_url = $httphost."/User/Meal";
                $addtime = date("Y-m-d H:i:s",time());
                $ip   = http_ip();
                $type = $postdata['type'];
                $trade_no = $postdata['WIDout_trade_no'];
                $name     = $postdata['WIDsubject'];
                $meals    = json_decode($conf['pay_meal'],true);
                $recharge = $postdata['WIDtotal_fee'];
               
                foreach ($meals as $item) {
                    if ($item['recharge'] == $recharge) {
                        $money = $item['money'];
                        break; // 找到匹配的数据后退出循环
                    }
                }
                if(!is_numeric($money) || $money < 0){
                    Commontc::falsetc('额度数额不合法！',rethreffun('./Meal'));
                }
                if(!is_numeric($recharge) || $recharge < 0){
                    Commontc::falsetc('金额不合法！',rethreffun('./Meal'));
                }
                $sql = "SELECT * FROM pay_user WHERE pid='{$conf['zero_pid']}' limit 1";
                $row = executeSQLQuery($sql);
                $parameter = array(
                		"type" => $type,
                		"notify_url"	=> $notify_url,
                		"return_url"	=> $return_url,
                		"out_trade_no"	=> $trade_no,
                		"name"	=> $name,
                		"money"	=> $recharge,
                		"sitename"	=> $conf['sitename'],
                		"ip"       =>$ip
                );
                if(!insertIntoInsideOrder($trade_no,$userrow['pid'],$recharge, $money))Commontc::falsetc('订单创建失败！',rethreffun('./Meal'));
                $this->Payment_channel($parameter,$row); 
                
            }
        }
        http_response_code(503);
    }
    public function submit_juhepay(){
        global $conf,$httphost;
        $postdata = input("post");
        if(!empty($postdata['WIDtotal_fee']) && !empty($postdata['pid']) && !empty($postdata['WIDout_trade_no']) && !empty($postdata['WIDsubject'])){
            $pid = $postdata['pid'];
            $sql = "SELECT * FROM pay_user WHERE pid=:pid limit 1";
            $date = array(
                'pid'=>$pid
                );
            $userrow = safeSqlQuery($sql,$date)['result'][0]??'';
            if(!$userrow)sysmsg('非法操作');
            $notify_url = $httphost."/User/api.php?s=notify_url";
            $return_url = $httphost."/SDK/cg";
            $addtime = date("Y-m-d H:i:s",time());
            $ip   = http_ip();
            $type = $postdata['type'];
            $trade_no = $postdata['WIDout_trade_no'];
            $name     = $postdata['WIDsubject'];
            $money = $postdata['WIDtotal_fee'];
            if(!is_numeric($money) || $money < 0){
                
                 Commontc::falsetc('金额不合法！',rethreffun('./login'));
            }
             $_zz_redirect = false;
            if(!$type){
                $_zz_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
                if (strpos($_zz_agent, 'alipayclient') !== false){
                    $type = 'alipay';
                }else if(strpos($_zz_agent, 'micromessenger') !== false){
                    $type = 'wxpay';
                }else if(preg_match('/qq\/[\d]/i', $_zz_agent) && strpos($_zz_agent, 'mqqbrowser') !== false){
                    $type = 'qqpay';
                }else{
                    $type = '';
                    $_zz_redirect = true;
                }
                if($type){
                    $sql = "SELECT * FROM pay_qrlist WHERE pid='{$pid}' and status = 1 and type = '{$type}'";
                    if(!executeSQLQuery($sql)){
                        $_zz_redirect = true;
                    }
                }
                if($_zz_redirect){
                    $_zz_qrs = safeSqlQuery("SELECT * FROM pay_qrlist WHERE pid=:pid AND status = 1", ['pid' => $pid]);

                    $hasAlipay = false;
                    $hasWeChat = false;
                    $hasQQPay = false;
                    $html = '';
                    foreach ($_zz_qrs['result'] as $_zz_qr) {
                        switch ($_zz_qr['type']) {
                            case 'alipay':
                                if (!$hasAlipay) {
                                    $_zz_name = '支付宝';
                                    $hasAlipay = true;
                                    $html.= '<option value="alipay">' . $_zz_name . '</option>';
                                }
                                break;
                            case 'wxpay':
                                if (!$hasWeChat) {
                                    $_zz_name = '微信';
                                    $hasWeChat = true;
                                    $html.= '<option value="wxpay">' . $_zz_name . '</option>';
                                }
                                break;
                            case 'qqpay':
                                if (!$hasQQPay) {
                                    $_zz_name = 'QQ钱包';
                                    $hasQQPay = true;
                                    $html.= '<option value="qqpay">' . $_zz_name . '</option>';
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    include usertem."cashier.php";
                    exit;
                }
                
            }
            $parameter = array(
            		"type" => $type,
            		"notify_url"	=> $notify_url,
            		"return_url"	=> $return_url,
            		"out_trade_no"	=> $trade_no,
            		"name"	=> $name,
            		"money"	=> $money,
            		"sitename"	=> $conf['sitename'],
            		"ip"       =>$ip
            );
            
            $this->Payment_channel($parameter,$userrow);
        }
        http_response_code(503);
    }
    public function notify_url(){
        global $date,$conf;
        $sql = "SELECT * FROM pay_user WHERE pid='{$conf['zero_pid']}' limit 1";
        $row = executeSQLQuery($sql);
        if(!$row)exit("false");
        $xfpay_config = payconf::epay($row);
        $epay = new epaysdk($xfpay_config);
        $verify_result = $epay->notify_url();
        if($verify_result){
            $out_trade_no = input("get")['out_trade_no'];
            $trade_status = input("get")['trade_status'];
            $name         = input("get")['name'];
            if($trade_status =='TRADE_SUCCESS'){
                $time= date("Y-m-d H:i:s",time());
                switch ($name){
                    case '申请商户':
                      User_Reg_notify_url($out_trade_no);
                    break;
                    case '额度充值':
                      User_quota_notify_url($out_trade_no);
                    break;
                    case '购买会员': 
                      User_payvip_notify_url($out_trade_no);
                    break;
                    case '购买额度套餐': 
                      User_quotapackage_notify_url($out_trade_no);
                    break;
                    case '购买套餐':
                      User_setmenu_notify_url($out_trade_no);
                    break;   
                }
            }
            echo "success";	
        }else{
            echo "false";
        }
    }
    
    //支付通道
    private  function Payment_channel($orderData,$row=null,$send=false){
           $xfpay_config = payconf::epay($row);
           $epay = new epaysdk($xfpay_config);
           if($send){
              return $epay->submit($orderData,true);
           }
       $epay->submit($orderData);
       exit;
   }
}


?>